package com.example.deepseek.backend.service;

import com.example.deepseek.backend.config.DeepSeekConfig;
import com.example.deepseek.backend.model.DeepSeekRequest;
import com.example.deepseek.backend.model.DeepSeekResponse;
import com.example.deepseek.backend.model.FileInfo;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

@Service
public class DeepSeekService {

    @Autowired
    private DeepSeekConfig config;

    @Autowired
    private RestTemplate restTemplate;

    @Value("${file.upload-dir}")
    private String uploadDir;

    // 处理文本消息
    public String processTextMessage(String message) {
        // 创建请求对象
        DeepSeekRequest request = new DeepSeekRequest();
        request.setModel("deepseek-chat"); // 替换为实际的模型名称
        
        // 添加消息
        List<DeepSeekRequest.Message> messages = new ArrayList<>();
        messages.add(new DeepSeekRequest.Message("user", message));
        request.setMessages(messages);
        
        // 发送请求并获取响应
        return sendRequestToDeepSeek(request);
    }

    // 处理文件消息（PDF）
    public String processFileMessage(MultipartFile file) throws IOException {
        // 保存上传的文件
        FileInfo fileInfo = saveUploadedFile(file);
        
        // 提取PDF文本内容
        String pdfContent = extractTextFromPDF(fileInfo.getUrl());
        
        // 构建提示词，包括PDF内容
        String prompt = "请分析以下PDF文件的内容，并提供摘要：\n" + pdfContent;
        
        // 创建请求对象
        DeepSeekRequest request = new DeepSeekRequest();
        request.setModel("deepseek-chat");
        
        // 添加消息
        List<DeepSeekRequest.Message> messages = new ArrayList<>();
        messages.add(new DeepSeekRequest.Message("user", prompt));
        request.setMessages(messages);
        
        // 发送请求并获取响应
        String response = sendRequestToDeepSeek(request);
        
        // 清理临时文件
        cleanupTempFile(fileInfo.getUrl());
        
        return response;
    }

    // 发送请求到DeepSeek API
    private String sendRequestToDeepSeek(DeepSeekRequest request) {
        // 创建HTTP头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + config.getApi().getKey());
        
        // 创建HTTP实体
        HttpEntity<DeepSeekRequest> entity = new HttpEntity<>(request, headers);
        
        try {
            // 发送请求
            ResponseEntity<DeepSeekResponse> response = restTemplate.exchange(
                    config.getApi().getUrl(),
                    HttpMethod.POST,
                    entity,
                    DeepSeekResponse.class
            );
            
            // 处理响应 - 兼容Spring 6.x
            if (response.getStatusCode().value() >= 200 && response.getStatusCode().value() < 300 && response.getBody() != null) {
                return response.getBody().getFirstAnswer();
            }
        } catch (Exception e) {
            // 处理异常
            e.printStackTrace();
            return "抱歉，处理请求时发生错误：" + e.getMessage();
        }
        
        return "抱歉，无法获取DeepSeek的响应。";
    }

    // 保存上传的文件
    private FileInfo saveUploadedFile(MultipartFile file) throws IOException {
        // 创建上传目录（如果不存在）
        Path uploadPath = Paths.get(uploadDir);
        if (!Files.exists(uploadPath)) {
            Files.createDirectories(uploadPath);
        }
        
        // 生成唯一文件名
        String fileName = System.currentTimeMillis() + "_" + file.getOriginalFilename();
        Path filePath = uploadPath.resolve(fileName);
        
        // 保存文件
        try (FileOutputStream fos = new FileOutputStream(filePath.toString())) {
            fos.write(file.getBytes());
        }
        
        // 返回文件信息
        FileInfo fileInfo = new FileInfo();
        fileInfo.setName(file.getOriginalFilename());
        fileInfo.setSize(file.getSize());
        fileInfo.setType(file.getContentType());
        fileInfo.setUrl(filePath.toString());
        
        return fileInfo;
    }

    // 从PDF文件中提取文本
    private String extractTextFromPDF(String filePath) throws IOException {
        try (PDDocument document = PDDocument.load(new File(filePath))) {
            PDFTextStripper pdfStripper = new PDFTextStripper();
            // 提取前10页（可根据需要调整）
            pdfStripper.setEndPage(Math.min(10, document.getNumberOfPages()));
            return pdfStripper.getText(document);
        }
    }

    // 清理临时文件
    private void cleanupTempFile(String filePath) {
        try {
            Files.deleteIfExists(Paths.get(filePath));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}